package controller;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import pojo.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;

import static java.lang.System.out;
import static java.lang.System.setOut;

@Controller
public class PaperController {
    String resource = "mybatis-config.xml";
    InputStream inputStream = Resources.getResourceAsStream(resource);
    SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
    SqlSession sqlSession = sqlSessionFactory.openSession();

    int t_id;//教师编号

    public PaperController() throws IOException {
    }

    //跳转到教师试题管理页面
    @RequestMapping("/toAddPaper")
    public String toAddPaperPage() {
        return "add_paper.jsp";
    }

    //教师查看所有试卷列表，createPaper页面
    @RequestMapping(value = "/loadPaperList")
    public String loadPaperList(HttpSession session) throws Exception {
        sqlSession.close();
        sqlSession=sqlSessionFactory.openSession();
        if(session.getAttribute("TEACHER_ID")==null){
            out.println("loadPaperList获取教师id失败");
        }
        else{
            t_id=(int)session.getAttribute("TEACHER_ID");//获取教师编号
            out.println("loadPaperList获取到的教师编号："+t_id);
            List<Paper> get_papers= sqlSession.selectList("mapper.Paper.searchNoPublishPaper",t_id);//通过教师编号找到该教师的所有试卷
            session.setAttribute("get_papers",get_papers);//设置session,在生成考试页面获取

        }
        return "createPaper.jsp";//返回生成考试页面，展示所有试卷列表
    }
    //    在试卷管理，createPaper页面查询未发布试卷
    @RequestMapping(value = "/searchPaperByName")
    public String searchPaperByName(Paper paper, HttpSession session) throws IOException {
        Paper p = new Paper();
        if(session.getAttribute("TEACHER_ID")==null){
            out.println("searchPaperByName获取教师id失败");
        }
        else {
            t_id = (int) session.getAttribute("TEACHER_ID");//获取教师编号
            p.setT_id(t_id);
            p.setP_name(paper.getP_name());
            List<Paper> get_papers = sqlSession.selectList("mapper.Paper.searchNoPublishPaperByName", p);//查询，通过教师编号及试卷名称查询该教师的所有未发布试卷
            if (get_papers == null) {
                out.println("数据为空");
            } else {
                session.setAttribute("get_papers", get_papers);//session设置，前端生成考试接收
            }
        }
        return "createPaper.jsp";//返回生成考试页面，展示查询到的试卷列表
    }

    //新增
    //跳转到教师查看试卷具体内容
    @RequestMapping("/loadPaperContent")
    public void loadPaperContent(@RequestParam(value="p_id")String p_id, HttpSession session,HttpServletResponse response,HttpServletRequest request) throws IOException {
        Object mess;
        out.println("loadPaperContent获取到的p_id:"+Integer.parseInt(p_id));
        Paper p=sqlSession.selectOne("mapper.Paper.findPaperTimeById",Integer.parseInt(p_id));//通过在前端获取到的p_id得到试卷的名字p_name
        out.println("loadPaperContent获取到的p_name:"+p.getP_name());
        session.setAttribute("p_name",p.getP_name());//通过session传递前端，watch_paper_content查看试卷具体内容时接收
        int p_id1=Integer.parseInt(p_id);//转为int类型
        sqlSession.close();//数据库先关闭再开启，连续两次查询之间清除缓存，保证数据更新
        sqlSession = sqlSessionFactory.openSession();
        List<Question> questionList= sqlSession.selectList("mapper.Point.findQ_idByP_id", p_id1);//通过试卷id在point表中获取所有试题id
        if(questionList!=null){
            request.getSession().setAttribute("questionList",questionList);//通过session传递前端，在watch_paper_content页面接收
            response.sendRedirect("watch_paper_content.jsp");
        }else{
            out.println("获取到的试题为空");
        }
    }

    //根据p_id判断数据库中是否已存在该教师，存在返回true
    public boolean isHaveT_id(int t_id){
        Teacher teacher = sqlSession.selectOne("mapper.Teacher.findTeacherByTeacherId",t_id);//根据id获取teacher对象，不为空则存在
        if(teacher!=null){
            //教师存在
            return true;
        }
        return false;
    }
    //新增试卷，并准备添加试题
    @RequestMapping(value = "/addPaper",method = RequestMethod.POST)
    public void addPaper(@RequestParam(value="p_name")String p_name, @RequestParam(value="t_id")String t_id, @RequestParam(value="starttime")String starttime, @RequestParam(value="endtime")String endtime,HttpServletResponse response,HttpServletRequest request) throws Exception {
        response.setContentType("text/html;charset=utf-8");//设置utf-8
        //PrintWriter out = response.getWriter();
        System.out.println("addPaper获取到的p_name:" + p_name);
        DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置格式
        Date start = format.parse(starttime);
        Date end = format.parse(endtime);//转换为了时间
        Object message=null;//用于传递弹窗信息
        if (start.compareTo(end) > 0) {//start>end,即start在end之后，不符合
            message = "添加试卷失败！请检查您选择的时间是否符合规范！";
            request.getSession().setAttribute("message", message);//传递弹窗信息
            response.sendRedirect("add_paper_new.jsp");
        } else if (!isHaveT_id(Integer.parseInt(t_id))) {//填入t_id,有可能填错，查找数据库是否有id，即判断是否存在该教师
            //教师不存在
            message = "添加试卷失败！请检查您输入的教师ID是否正确！";
            request.getSession().setAttribute("message", message);
            response.sendRedirect("add_paper_new.jsp");
        } else {//正确，可以成功添加
            Paper p = new Paper();
            p.setP_name(p_name);
            p.setT_id(Integer.parseInt(t_id));//input传过来是string，转换为int
            long s = start.getTime();
            long e = end.getTime();
            Timestamp stime = new Timestamp(s);
            Timestamp etime = new Timestamp(e);//都转换为时间戳，方便储存在model里
            p.setStarttime(stime);
            p.setEndtime(etime);
            int rows = sqlSession.insert("mapper.Paper.addPaper", p);//插入试卷数据
            sqlSession.commit();//提交更新数据库
            if (rows > 0) {
                //新增成功后，将试卷id也一起传到add_paper.jsp
                Paper pp=sqlSession.selectOne("mapper.Paper.findIdByName",p);//通过名字找到该试卷
                request.getSession().setAttribute("paper",pp);//设置session，传递到前端
                message = "添加试卷成功！请选择试题加入该试卷吧!";
                request.getSession().setAttribute("message", message);
                response.sendRedirect("QuestionList");//传递到该方法，获取试题列表，并准备将试题添加到刚才新增的试卷中
            } else {
                message = "添加试卷失败!";
                request.getSession().setAttribute("message", message);
                response.sendRedirect("toAddPaper");//失败，重新返回添加页面
            }
        }
    }


    //
    //删除试卷
    @RequestMapping("/deletePaper")
    public void deletePaper(@RequestParam(value="p_id")String p_id,HttpServletResponse response,HttpServletRequest request) throws IOException{
        Object mess;
        String p_id1=p_id.trim();//去除多余空格
        out.println("删除试卷获取到的试卷id："+Integer.parseInt(p_id1));
        int id=Integer.parseInt(p_id1);//转换为int
        int rows1=sqlSession.delete("mapper.Paper.deletePaper",id);//删除对应试卷
        int rows2=sqlSession.delete("mapper.Point.deletePoint",id);//试卷里对应的试题和分数也删除
        sqlSession.commit();//提交更新数据库
        if(rows1>0){//成功删除
            out.println("您成功删除了"+rows1+"条试卷数据！\n");
            out.println("您成功删除了"+rows2+"条试卷对应的试题数据！\n");
            //重定向到试题页面
            mess = "成功删除试卷及试卷中所有试题!";
            request.getSession().setAttribute("message", mess);
            response.sendRedirect("loadPaperList");//返回到试卷列表页面，并及时更新
        } else{
            out.println("删除试卷失败！\n");
            mess = "删除试卷失败!";
            request.getSession().setAttribute("message", mess);
            response.sendRedirect("loadPaperList");//返回到试卷列表页面
        }
    }
}
